package com.apobates.forum.bucket.servlet;

import com.apobates.forum.utils.Commons;
import com.apobates.forum.utils.DateTimeUtils;
import com.apobates.forum.utils.fileupload.UploadInitParamers;
import com.apobates.forum.utils.fileupload.ckeditor.CKEditorHightHandler;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Optional;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * CKEditor的上传
 *
 * @author xiaofanku
 * @since 20200528
 */
public class UploadEditorFileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String uploadImageDirectName;
    private String siteDomain;
    private long uploadMaxByte;
    private final static Logger logger = LoggerFactory.getLogger(UploadEditorFileServlet.class);
    
    /**
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //子目录
        String childDirect = DateTimeUtils.getYMD();
        // 项目路径
        final String realPath = request.getServletContext().getRealPath("/") + File.separator + uploadImageDirectName + File.separator + childDirect;
        // 前台访问路径
        final String frontVisitPath = siteDomain + uploadImageDirectName + "/" + childDirect + "/";
        UploadInitParamers cip = new UploadInitParamers() {
            @Override
            public String getFileSaveDir() {
                return realPath;
            }
            @Override
            public Optional<String> getCallbackFunctionName() {
                // 没有回调函数
                return Optional.empty();
            }
            @Override
            public String getUploadFileInputName() {
                return "upload";
            }
            @Override
            public HttpServletRequest getRequest() {
                return request;
            }
        };
        String outResult;
        try {
            ServletFileUploadConnector connector = new ServletFileUploadConnector(new CKEditorHightHandler(frontVisitPath, uploadMaxByte));
            String responsebody = connector.upload(cip);
            outResult = CKEditorHightHandler.buildCkeditorResponse(true, "上传成功", responsebody.replace(frontVisitPath, ""), responsebody);
        } catch (IOException | ServletException e) {
            String errorMesg = e.getMessage();
            logger.info("[UEFS]异常消息: " + errorMesg);
            if (logger.isDebugEnabled()) {
                logger.debug(errorMesg, e);
            }
            outResult = CKEditorHightHandler.buildCkeditorResponse(false, errorMesg);
        }
        logger.info("[UEFS]输出响应: " + outResult);
        //
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        try (PrintWriter out = response.getWriter()) {
            out.write(outResult);
            out.flush();
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        try (PrintWriter out = resp.getWriter()) {
            out.println("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>Access Denied</title></head><body><p>暂不支持浏览功能</p></body></html>");
            out.flush();
        }
    }
    
    /**
     * 获得初始化值
     * @param config
     * @throws javax.servlet.ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        this.siteDomain = config.getInitParameter("siteDomain"); //站点URL, http://xx.com
        this.uploadImageDirectName = config.getInitParameter("uploadImageDirectName"); //图片保存的目录
        this.uploadMaxByte = Commons.stringToLong(config.getInitParameter("uploadMaxByte"), 5242880L); //5M|//multipart-config.max-request-size
    }
}